package com.qianfeng.openplatform.auther.controller;

import com.fasterxml.jackson.databind.ser.Serializers;
import com.qianfeng.openplatform.auther.bean.User;
import com.qianfeng.openplatform.auther.feign.CacheService;
import com.qianfeng.openplatform.commons.beans.BaseResultBean;
import com.qianfeng.openplatform.commons.constans.SystemParams;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.time.Instant;
import java.util.Date;

@RestController
public class AutherController {
    @Autowired
    private CacheService cacheService;

    @RequestMapping("/login")
    public BaseResultBean auther(@RequestBody User user, HttpServletResponse response) {
        BaseResultBean bean = new BaseResultBean();

        if ("admin".equals(user.getUserName()) && "admin".equals(user.getPassword())) {
            //帐号信息是对的,直接给用户返回JWT相关的信息
            bean.setCode("1");
            bean.setMsg("登陆成功");
            Instant now = Instant.now();
            String jwt = Jwts.builder()

                    .setSubject("admin")//设置当前的用户是谁
                    .setIssuedAt(Date.from(now))//设置开始的有效期
                    .setExpiration(Date.from(now.plusSeconds(3600)))//设置过期时间我当前时间顺眼一小时
                    .claim("id", 1)//可以随便内容,主要是键值对,可以在需要的地方拿出来
                    .claim("quanxian", "ADMIN")
                    .signWith(SignatureAlgorithm.HS256,"meiyoumima".getBytes())//设置签名的算法和秘钥值
                    .compact();
            System.err.println(jwt);
            //我们自己定义一个规范,我们会将token放到响应头中返回
            response.addHeader("token",jwt);
            try {
                cacheService.save2Redis(SystemParams.JWT_TOKEN_REDIS_PRE + user.getUserName(), jwt,3600*1000);//向redis中保存用户的jwt
            } catch (Exception e) {
                e.printStackTrace();
            }
        }else{
            bean.setCode("0");
            bean.setMsg("帐号密码错误");
        }

        return bean;
    }
}
